import { RoleHelper } from "./base.role";
import { Transporter } from "./transporter.role";

export class Builder implements IRole {
    role: RoleType = 'builder';
    bodyPart: BodyPartConstant[] = [WORK, CARRY, MOVE];
    priority: number = 4;
    minCost: number = 200;

    work(creep: Creep) {
        this.stateSwitch(creep);

        if (creep.memory.working) {
            // 修建
            RoleHelper.build(creep);

        } else {
            // 1. 获取存储的能源
            if (RoleHelper.getStoreEnergy(creep)) {
                return;
            }

            // 2. 拾取地上的能源
            if (RoleHelper.pickupEnergy(creep)) {
                RoleHelper.harvestEnergy(creep);
                return;
            }

            // 3. 采集能源
            if (RoleHelper.harvestEnergy(creep)) {
                return;
            }

            return;
        }
    }

    stateSwitch(creep: Creep) {
        if (creep.memory.working === undefined) {
            creep.memory.working = false;
        }

        if (creep.store.getFreeCapacity() === 0) {
            // 背包满了，切换至修建状态
            creep.memory.working = true;
        } else if (creep.store.getUsedCapacity() === 0) {
            // 背包空了，切换至取能状态
            creep.memory.working = false;
        }
    }

    // 修建
    private build(creep: Creep): boolean {
        const target = this.findBuildTarget(creep);

        if (target) {
            const result = creep.build(target);
            if (result === ERR_NOT_IN_RANGE) {
                RoleHelper.moveToTarget(creep, target, '#ff7700');
                creep.say('🏗️去工地');
            } else if (result === OK) {
                creep.say('🔧建设中');
            }
            return true;
        }

        return false;
    }

    private findBuildTarget(creep: Creep): any | null {
        const buildTarget = creep.pos.findClosestByPath(FIND_MY_CONSTRUCTION_SITES);
        return buildTarget;
    }

    // 维修
    private repair(creep: Creep): boolean {
        const target = this.findRepairTarget(creep);

        if (target) {
            const result = creep.repair(target);
            if (result === ERR_NOT_IN_RANGE) {
                RoleHelper.moveToTarget(creep, target, '#55ff77');
                creep.say('🏗️去修复')
            } else if (result === OK) {
                creep.say('🔧修复中');
            }

            return true;
        }

        return false;
    }

    // 找到维修建筑
    private findRepairTarget(creep: Creep): AnyStructure | null {
        const repairTarget = creep.pos.findClosestByPath(FIND_STRUCTURES, {
            filter: s => s.hits < s.hitsMax &&
                s.structureType !== STRUCTURE_WALL &&
                s.structureType !== STRUCTURE_RAMPART
        })

        return repairTarget;
    }
}